#!/usr/bin/env python
# @Date    : 2023-01-17
# @Author  : Bright (brt2@qq.com)
# @Link    : https://gitee.com/brt2
# @Version : 0.1.4

import sublime
import sublime_plugin

import os
import webbrowser

#####################################################################
# import sys

# CURR_DIR = os.path.dirname(__file__)
# DIR_SITE_PACKAGES = os.path.join(CURR_DIR, "site-packages")
# if DIR_SITE_PACKAGES not in sys.path:
#     sys.path.append(DIR_SITE_PACKAGES)
#####################################################################

from xmlrpc.client import ServerProxy

# curr_dir = os.path.dirname(__file__)
# sys.path.append(curr_dir)
# from server.rpi import RPI_SERVICE_PORT
RPI_SERVICE_PORT = 2180
HOST = None
rpcclt = None

class RpiConnectCommand(sublime_plugin.WindowCommand):
    """ 拉取远程仓库的文件 """
    path_rdphost_ini = os.path.expanduser("~/.ssh/rdp-hosts.ini")

    def _reload_projects(self):
        from configparser import ConfigParser

        cfg = ConfigParser()
        cfg.read(self.path_rdphost_ini, encoding='utf-8')
        self.list_names = cfg.sections()
        self.list_hosts = [cfg[key]["Host"] for key in self.list_names]

    def run(self, type="preset"):
        if type == "preset":
            self._reload_projects()
            self.window.show_quick_panel(self.list_names, self.on_panel_done, 0, 0)
        elif type == "input":
            self.window.show_input_panel("ServHost: ", "192.168.43.x",
                                         self.on_panel_done, None, self.on_panel_cancel)
        else:
            raise NotImplementedError()

    def on_panel_done(self, data):
        if isinstance(data, int):
            if data < 0:
                """ 取消输入或选取 """
                print("[-] 取消输入")
                return
            host = self.list_hosts[data]

        # 处理部分动态host
        if self.list_names[data] == "hotspot":
            import subprocess
            import platform

            if platform.system() == "Windows":
                host = subprocess.check_output('route print 0.0.0.0 |findstr "{}" '.format(host), shell=True)
                host = host.decode().split()[2]
            else:
                host = subprocess.check_output("route print 0.0.0.0 |grep '{}' |awk '{print $3}'".format(host), shell=True)
                host = host[0]

        # 连接远程RPCServer
        global rpcclt, HOST
        HOST = host
        rpcclt = ServerProxy('http://{}:{}'.format(HOST, RPI_SERVICE_PORT))
        try:
            data = rpcclt.run_codelines("print('Hi, Sublime')")
            print(data)
        except Exception as e:
            sublime.message_dialog("[!] 服务器【{}】连接失败: {}".format(host, e))

    def on_panel_change(self, data):
        print(">>>", data)

    def on_panel_cancel(self):
        """ 取消输入 """

class RpiCloseCommand(sublime_plugin.WindowCommand):
    def run(self):
        rpcclt.__close()

class RpiShowCommand(sublime_plugin.WindowCommand):
    def run(self):
        webbrowser.open_new_tab('http://{}:{}/'.format(HOST, RPI_SERVICE_PORT))

class RpiRuncodeCommand(sublime_plugin.TextCommand):
    def run(self, edit, goto_next=False):
        list_sel = self.view.sel()
        assert len(list_sel) == 1, "runcode不支持多光标操作"
        sel = list_sel[0]

        block_mode = sel.begin() == sel.end()  # 非block模式，则仅作为选取var时check_varible
        if block_mode:
            source = self._get_cell_source(sel.begin()).strip() + "\n"
        else:
            source = self.view.substr(sel)  # variable

        # run_cell_source
        ret = rpcclt.run_codelines(source)
        print("[rpi]\n" + ret if ret else "[rpi]")

        if goto_next and block_mode:
            # 鼠标跳至下一个cell
            self.view.sel().clear()
            self.view.sel().add(self.next_cell)
            self.view.show_at_center(self.next_cell)

    def _get_cell_source(self, sel_pos):
        cells = self.view.find_all("^# %%")
        if len(cells) == 0:
            sublime.message_dialog("[!] 当前文档未发现分块，请添加“# %%”标识")
            return

        curr_cell_range = [0, -1]
        for region in cells:
            # if region.contains(sel):
            n_start, n_end = region.begin(), region.end()
            if n_start > sel_pos:
                curr_cell_range[1] = n_start
                self.next_cell = self.view.full_line(n_end).end()
                break
            else:  # n_start <= sel_pos
                curr_cell_range[0] = self.view.full_line(n_end).end()  # 跳过# %% 整行
        else:
            view_region = self.view.visible_region()
            curr_cell_range[1] = view_region.end()

        return self.view.substr(sublime.Region(*curr_cell_range))
